<?php

namespace app\speedDating\services\common;

use app\speedDating\exception\ServiceRuntimeException;

class UtilsService
{
    /**
     * 生成hash值
     * @param $value
     * @param array $options
     * @return string|null
     */
    public static function bcryptHash($value, array $options = [])
    {
        $hash = password_hash($value, PASSWORD_BCRYPT, [
            'cost' => $options['rounds'] ?? 10,
        ]);

        if ($hash === false) {
            throw new ServiceRuntimeException('Bcrypt hashing not supported.');
        }

        return $hash;
    }

    /**
     * 明文与hash值进行对比
     * @param $value
     * @param $hashedValue
     * @return bool
     */
    public static function bcryptVerify($value, $hashedValue)
    {
        if (strlen($hashedValue) === 0) {
            return false;
        }

        return password_verify($value, $hashedValue);
    }

    /**
     * 对子符合条件字符串进行隐私转换
     * @param $string
     * @return string
     */
    public static function compileStr($string)
    {
        if (($len = strlen($string)) >= 3) {
            $sLen = $eLen = floor($len / 3);
        } else {
            return $string;
        }

        return substr($string, 0, $sLen) . "***" . substr($string, -$eLen);
    }


    /**
     * 获取网站
     * @return string
     */
    public static function domain(): string
    {
        $domain = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $domain .= "://" . $_SERVER['HTTP_HOST'] . '/';
        return $domain;
    }

    /**
     * 内存监控
     * @param $location 位置描述
     * @param $firstM   当前量
     * @return void
     */
    public static function meM($location, &$firstM)
    {
        $lastM = sprintf("%.4f", memory_get_usage() / (1024 * 1024));
        $lastMMax = sprintf("%.4f", memory_get_peak_usage() / (1024 * 1024));
        $change = sprintf("%.4f", $lastM - $firstM);
        $symbol = ($lastM >= $firstM) ? '+' : '-';
        $s = ($firstM == 0) ? '--' : $symbol . $change;
        dump('Memory#' . $location . '节点内存：' . $lastM . '\M 内存变化: ' . $s . '\m' . '  区域峰值：' . $lastMMax . '\M');
        $firstM = $lastM;
        unset($lastM, $lastMMax, $change, $symbol, $s);
    }
}